package com.client.service;

import com.client.entity.B_client;
import com.client.entity.Message;
import com.client.utils.AESutil;
import com.client.utils.MessageUtils;
import com.client.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

//存储消息，毕竟一时半会学不会消息队列，就先凑合用吧
@Slf4j
@Service
public class MessageService {
    //认证对象的存储
    private static Map<String, B_client> b_clients = new HashMap<>();
    //消息重发的队列
    private static List<Message> messages = new ArrayList<>();

    //建立新的认证过程
    public boolean newClient(UUID uid, String id, int port, String ip) {
        if (b_clients.containsKey(id)) {
            return false;
        } else {
            B_client b_client = new B_client(id, port,
                    ip, 1, 0, 0, new Date(new Date().getTime()), uid);
            b_clients.put(id, b_client);
            return true;
        }
    }

    //从认证列表中获得对应的对象
    public B_client getClient(String name) {
        return b_clients.get(name);
    }

    //从认证列表中获得对应的对象
    public B_client getClient(UUID uid) {
        for (Map.Entry<String, B_client> client : b_clients.entrySet()) {
            if (client.getValue().getUid().equals(uid)) {
                return client.getValue();
            }
        }
        return null;
    }

    //删除认证对象
    public void deleteClient(String name) {
        b_clients.remove(name);
    }

    public static void addMessage(String uid, String ip, Integer port, byte[] msg, Date time, int interval_time, int timeout) {
        messages.add(new Message(uid, ip, port, msg, time, interval_time, timeout));
    }

    public static void deleteMessage(String uid) {
        messages.removeIf(message -> message.getUid().equals(uid));
    }

    public List<Message> getMessages() {
        return messages;
    }

    public Map<String, B_client> getClients() {
        return b_clients;
    }

    //确认收到消息
    public static byte[] MessageConfirm(byte[] k, UUID uid, String myid) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> result = new HashMap<>();
        map.put("type","CONFIRM_GET_PACKET");

        result.put("id", myid);
        result.put("time", MessageUtils.getNowTime());
        result.put("uid", uid);
        result.put("uuid", MessageUtils.getuuid());
        result.put("body", AESutil.encrypt(Utils.getByteFromObjectMap(map), k));
        result.put("hash", MessageUtils.HashOfFormal(result, k));

        return Utils.getByteFromObjectMap(result);
    }
}
